package com.ruyiadmin.springcloud.producer.controller.business.module;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruyiadmin.springcloud.producer.common.annotations.system.Log;
import com.ruyiadmin.springcloud.producer.common.annotations.system.Permission;
import com.ruyiadmin.springcloud.producer.common.core.business.enums.OperationType;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.ActionResult;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryCondition;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryItem;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.QueryResult;
import com.ruyiadmin.springcloud.producer.common.core.system.enums.DataType;
import com.ruyiadmin.springcloud.producer.common.core.system.enums.QueryMethod;
import com.ruyiadmin.springcloud.producer.common.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springcloud.producer.domain.entity.business.module.BizModule;
import com.ruyiadmin.springcloud.producer.domain.entity.business.module.BizUserModule;
import com.ruyiadmin.springcloud.producer.service.iservices.business.module.IBizModuleService;
import com.ruyiadmin.springcloud.producer.service.iservices.business.module.IBizUserModuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 业务模块表 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-12
 */
@RestController
@RequestMapping("/BizModuleManagement")
@Api(tags = "系统业务模块管理服务")
@RequiredArgsConstructor
public class BizModuleController {

    //region 模块服务私有属性

    private final IBizModuleService bizModuleService;
    private final IBizUserModuleService bizUserModuleService;

    //endregion

    //region 查询业务模块列表

    @PostMapping("/Post")
    @ApiOperation(value = "查询业务模块列表")
    @Log(OperationType = OperationType.QueryList)
    @Permission(permission = "biz:module:list")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public QueryResult<BizModule> queryByPage(@RequestBody QueryCondition queryCondition)
            throws ExecutionException, InterruptedException {
        CompletableFuture<QueryResult<BizModule>> future = CompletableFuture.supplyAsync(() -> {
            QueryWrapper<BizModule> wrapper = new QueryWrapper<>();//设置条件
            queryCondition.getQueryWrapper(wrapper);//转化查询条件、转化排序条件

            Page<BizModule> page = new Page<>(queryCondition.getPageIndex(),
                    queryCondition.getPageSize());//初始化page

            this.bizModuleService.page(page, wrapper);//执行查询
            long total = page.getTotal();//总数
            List<BizModule> rs = page.getRecords();//结果

            return QueryResult.success(total, rs);
        });
        return future.get();
    }

    //endregion

    //region 查询业务模块信息

    @GetMapping("/GetById/{moduleId}")
    @ApiOperation(value = "查询业务模块信息")
    @Log(OperationType = OperationType.QueryEntity)
    @Permission(permission = "biz:module:list")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult getById(@PathVariable("moduleId") String moduleId)
            throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResult> future = CompletableFuture.supplyAsync(() ->
                ActionResult.success(this.bizModuleService.getById(moduleId)));
        return future.get();
    }

    //endregion

    //region 新增业务模块信息

    @PostMapping("/Add")
    @ApiOperation(value = "新增业务模块信息")
    @Log(OperationType = OperationType.AddEntity)
    @Permission(permission = "module:add:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult add(@Valid @RequestBody BizModule bizModule) {
        return ActionResult.success(this.bizModuleService.save(bizModule));
    }

    //endregion

    //region 编辑业务模块信息

    @PutMapping("/Put")
    @ApiOperation(value = "编辑业务模块信息")
    @Log(OperationType = OperationType.EditEntity)
    @Permission(permission = "module:edit:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult edit(@Valid @RequestBody BizModule bizModule) {
        return ActionResult.success(this.bizModuleService.updateById(bizModule));
    }

    //endregion

    //region 批量删除业务模块

    @DeleteMapping("/DeleteRange/{ids}")
    @ApiOperation(value = "批量删除业务模块")
    @Log(OperationType = OperationType.DeleteEntity)
    @Permission(permission = "module:del:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult deleteRange(@PathVariable("ids") String ids) {
        //批量删除业务模块检测
        this.deleteCheck(ids);
        //删除数据
        List<String> array = Arrays.asList(ids.split(","));
        return ActionResult.success(this.bizModuleService.removeByIds(array));
    }

    //endregion

    //region 查询无权限模块列表

    @GetMapping("/GetUserNonModules/{userId}")
    @ApiOperation(value = "查询无权限模块列表")
    @Log(OperationType = OperationType.QueryList)
    @Permission(permission = "biz:module:list")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public QueryResult<BizModule> queryUserNonModules(@PathVariable("userId") String userId)
            throws ExecutionException, InterruptedException {
        CompletableFuture<QueryResult<BizModule>> future = CompletableFuture.supplyAsync(() ->
                this.bizModuleService.queryUserNonModules(userId));
        return future.get();
    }

    //endregion

    //region 批量删除业务模块检测

    /**
     * 批量删除业务模块检测
     *
     * @param ids 编号数组
     */
    private void deleteCheck(String ids) {
        String[] array = ids.split(",");
        //删除校验
        for (String item : array) {
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setQueryItems(new ArrayList<>());
            queryCondition.getQueryItems().add(
                    new QueryItem("MODULE_ID", DataType.Guid, QueryMethod.Equal, item));

            QueryWrapper<BizUserModule> wrapper = new QueryWrapper<>();
            queryCondition.getQueryWrapper(wrapper);

            int count = this.bizUserModuleService.list(wrapper).size();
            if (count > 0) {
                throw new RuYiAdminCustomException("module has been used,can not be deleted");
            }
        }
    }

    //endregion

}
